<template>
  <div class="app-container">
    <el-form :model="form" ref="form" label-width="200px" v-loading="formLoading" :rules="rules">
      <el-form-item label="手机号：" prop="user.phone" required>
        <el-input v-model="form.user.phone"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名：" prop="user.realName" required>
        <el-input v-model="form.user.realName"></el-input>
      </el-form-item>
      <el-form-item label="人员类别：" prop="user.departmentId" required>
        <el-tree-select v-model="form.user.departmentId" :data="departmentTree" check-strictly
          :render-after-expand="true" default-expand-all placeholder="人员类别" />
      </el-form-item>
      <el-form-item label="头像：" prop="imagePath">
        <el-upload class="upload" action="/api/upload/folder/file" accept=".jpg,.png" :data="{ folder: 'profile' }"
          :show-file-list="false" :on-progress="uploadProgress" :on-success="uploadSuccess" :on-error="uploadError"
          :before-upload="handleBeforeUpload">
          <el-avatar :size="100" :src="form.user.imagePath" shape="circle" fit="scale-down" class="user-image">暂无头像
          </el-avatar>
        </el-upload>
      </el-form-item>
      <el-form-item label="职位：" prop="user.jobTitle" required>
        <el-input v-model="form.user.jobTitle"></el-input>
      </el-form-item>
      <el-form-item label="身份证号：" prop="user.idCard" required>
        <el-input v-model="form.user.idCard"></el-input>
      </el-form-item>
      <el-form-item label="年龄：" prop="user.age" required>
        <el-input v-model.number="form.user.age"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="user.sex" required>
        <el-select v-model="form.user.sex" placeholder="性别" clearable>
          <el-option v-for="item in EnumMap.user.sexEnum" :key="item.key" :value="item.key"
            :label="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="健康状况：" prop="userExtend.health" required>
        <el-input v-model="form.userExtend.health"></el-input>
      </el-form-item>
      <el-form-item label="参加工作时间：" prop="userExtend.workTime" required>
        <el-date-picker v-model="form.userExtend.workTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="在职教育毕业院校及专业：" prop="userExtend.jobEducationMajor" required>
        <el-input v-model="form.userExtend.jobEducationMajor"></el-input>
      </el-form-item>
      <el-form-item label="工作单位及职务/工种：" prop="userExtend.workUnitType" required>
        <el-input v-model="form.userExtend.workUnitType"></el-input>
      </el-form-item>
      <el-form-item label="通信地址及邮编：" prop="userExtend.mailAddressCode" required>
        <el-input v-model="form.userExtend.mailAddressCode"></el-input>
      </el-form-item>
      <el-form-item label="状态：" prop="user.status" required>
        <el-select v-model="form.user.status" placeholder="状态">
          <el-option v-for="item in EnumMap.user.statusEnum" :key="item.key" :value="item.key"
            :label="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资料上传：" prop="fileList">
        <UserTabDataUpload DictType="user_file_type" v-model:fileList="form.fileList" :userInfo="form.user">
        </UserTabDataUpload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { EnumMap } from '@/api/EnumMap';
import { employeeSelect, employeeEdit } from '@/api/user';
import { tree } from '@/api/department';
import useStore from '@/store';
import UserTabDataUpload from '@/components/UserTabDataUpload/index.vue';
const { tagsView } = useStore();

export default {
  name: 'EmployeeEdit',
  components: { UserTabDataUpload },
  data() {
    return {
      EnumMap: EnumMap,
      form: {
        user: {
          id: null,
          realName: null,
          idCard: null,
          imagePath: null,
          jobTitle: null,
          systemRole: 1,
          status: 1,
          age: null,
          sex: null,
          phone: null,
          departmentId: null
        },
        userExtend: {
          health: null,
          jobEducationMajor: null,
          mailAddressCode: null,
          trainAttendance: null,
          trainOpinion: null,
          unitOpinion: null,
          workTime: null,
          workUnitType: null
        }
      },
      departmentTree: [],
      formLoading: false,
      rules: {
        'user.phone': [{ required: true, trigger: 'blur', validator: this.validatePhoneNumber }],
        'user.idCard': [{ required: true, message: '请输入身份证号' }],
        'user.departmentId': [{ required: true, message: '请选择人员类别' }],
        'user.jobTitle': [{ required: true, message: '请输入职位' }],
        'user.sex': [{ required: true, message: '请选择性别' }],
        'userExtend.health': [{ required: true, message: '请输入健康状况' }],
        'userExtend.workTime': [{ required: true, message: '请选择参加工作时间' }],
        'userExtend.jobEducationMajor': [{ required: true, message: '请输入在职教育毕业院校及专业' }],
        'userExtend.workUnitType': [{ required: true, message: '请输入工作单位及职务/工种' }],
        'userExtend.mailAddressCode': [{ required: true, message: '请输入通信地址及邮编' }],
        'user.status': [{ required: true, message: '请选择状态' }],
        'user.realName': [
          { required: true, message: '请输入真实姓名' },
          {
            max: 255,
            message: '长度小于255个字符'
          }
        ],
        'user.age': [{ required: true, type: 'number', message: '年龄必须为数字值' }],
      }
    };
  },
  created() {
    let id = this.$route.query.id;

    if (id && parseInt(id) !== 0) {
      this.formLoading = true;
      employeeSelect(id)
        .then(re => {
          console.log(re);
          this.form = re.response;
        })
        .finally(() => {
          this.formLoading = false;
        });
    }

    tree().then(re => {
      this.departmentTree = re.response;
    });
  },
  methods: {
    submitForm() {
      console.log('23123');
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          employeeEdit(this.form)
            .then(re => {
              if (re.code === 1) {
                this.$message.success(re.message);
                tagsView.delCurrentView(this).then(() => {
                  this.$router.push('/user/employee/list');
                });
              } else {
                this.$message.error(re.message);
              }
            })
            .finally(() => {
              this.formLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    handleBeforeUpload(file) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = 200; // 设置压缩后图片宽度
            // canvas.height = (img.height / img.width) * 300; // 根据宽度等比缩放高度
            canvas.height = 300; // 根据宽度等比缩放高度
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            canvas.toBlob(
              (blob) => {
                resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() }));
              },
              'image/jpeg',
              0.9 // 压缩质量，0.9表示压缩率为90%
            );
          };
        };
      })
    },
    uploadProgress() {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      });
    },
    uploadSuccess(re, file) {
      console.log(re, '图片');
      this.loading.close();
      if (re.code === 1) {
        this.form.user.imagePath = re.response.path;
      } else {
        this.$message.error(re.message);
      }
    },
    uploadError() {
      this.loading.close();
      this.$message.error('文件上传失败，请检查文件大小或文件格式');
    },
    resetForm() {
      this.form = {
        id: null,
        realName: null,
        idCard: null,
        imagePath: null,
        jobTitle: null,
        systemRole: 1,
        status: 1,
        age: null,
        sex: null,
        phone: null,
        departmentId: null
      };
      this.$refs['form'].resetFields();
    },
    validatePhoneNumber(rule, value, callback) {
      const reg = /^1[3-9]\d{9}$/
      if (!value) {
        callback(new Error('手机号不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    },
  }
};
</script>
